﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Forms;
using System.Windows.Input;
using System.Windows.Interop;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;

namespace sunsetmp
{
    /// <summary>
    /// Interaction logic for PlayerWindow.xaml
    /// </summary>
    public partial class PlayerWindow : Window
    {
        Core core;
        ThicknessAnimation leftOpenAnimation;
        ThicknessAnimation leftCloseAnimation;
        ThicknessAnimation rightOpenAnimation;
        ThicknessAnimation rightCloseAnimation;
        DoubleAnimation BodyToTitleAnimations;
        DoubleAnimation TitleToBodyAnimatoins;
        DoubleAnimation TitleToWindowAnimations;
        DoubleAnimation WindowToTitleAnimations;
        DoubleAnimation BodyToWindowAnimations;
        DoubleAnimation WindowToBodyAnimations;
        DoubleAnimation rotateAnimation;
        public bool doAnimation = false;
        public double openedWindowHeight = 250;
        bool spoilerOpen = false;
        bool titleOpened = false;
        bool webWinOpened = false;
        bool locWinOpened = false;
        bool isTop = false;
        public int selectedTab;
        bool? selectedUserWall = null;
        bool? selectedGroupWall = false;
        bool? selectedFriendWall = false;

        //--------------------------------------------------------------------------------------
        #region Главное Окно
        public PlayerWindow()
        {
            
            if (CheckDataBaseEngine() == false)
                System.Windows.Application.Current.Shutdown();
            string currentDir = System.IO.Path.GetDirectoryName(System.Windows.Forms.Application.ExecutablePath);
            if (Properties.Settings.Default.DontCheckUpdate == false)
            {
                CheckUpdate cu = new CheckUpdate(currentDir + "\\", @"ftp://sunset:4815162342@irvinspace.ru/http/");
            }
            core = new Core(this);
            InitializeComponent();
            Duration duration = new Duration(TimeSpan.Parse("0:0:0.3"));
            var UPduration = new Duration(TimeSpan.Parse("0:0:0.4"));
            Duration rotateDuration = TimeSpan.FromSeconds(3);
            double closedSlider = 50;
            double openedTitle = 76;
            var lFrom = new Thickness(0, 0, 110, 0);
            var lTo = new Thickness(0, 0, 285, 0);
            var rFrom = new Thickness(110, 0, 0, 0);
            var rTo = new Thickness(285, 0, 0, 0);
            var updownFrom = new Thickness(0, 25, 0, 25);
            var upTo = new Thickness(0, 0, 0, 25);
            var downTo = new Thickness(0, 25, 0, 0);
            leftOpenAnimation = new ThicknessAnimation(lFrom, lTo, duration);
            leftCloseAnimation = new ThicknessAnimation(lTo, lFrom, duration);
            rightOpenAnimation = new ThicknessAnimation(rFrom, rTo, duration);
            rightCloseAnimation = new ThicknessAnimation(rTo, rFrom, duration);
            ///////
            BodyToTitleAnimations = new DoubleAnimation(closedSlider, openedTitle, UPduration);
            TitleToBodyAnimatoins = new DoubleAnimation(openedTitle, closedSlider, UPduration);
            ///////
            TitleToWindowAnimations = new DoubleAnimation(openedTitle, openedWindowHeight, UPduration);
            TitleToWindowAnimations.FillBehavior = FillBehavior.Stop;
            TitleToWindowAnimations.Completed += TitleToWindowAnimations_Completed;
            WindowToTitleAnimations = new DoubleAnimation(openedWindowHeight, openedTitle, UPduration);
            WindowToTitleAnimations.FillBehavior = FillBehavior.Stop;
            WindowToTitleAnimations.Completed += WindowToTitleAnimations_Completed;
            ///////
            BodyToWindowAnimations = new DoubleAnimation(closedSlider, openedWindowHeight, UPduration);
            BodyToWindowAnimations.FillBehavior = FillBehavior.Stop;
            BodyToWindowAnimations.Completed += BodyToWindowAnimations_Completed;
            WindowToBodyAnimations = new DoubleAnimation(openedWindowHeight, closedSlider, UPduration);
            WindowToBodyAnimations.FillBehavior = FillBehavior.Stop;
            WindowToBodyAnimations.Completed += WindowToBodyAnimations_Completed;
            if (Properties.Settings.Default.ShowMenuInStart)
                OpenCloseSpoiler('l');
            timelineSlider.AddHandler(MouseLeftButtonDownEvent, new MouseButtonEventHandler(timelineSlider_MouseLeftButtonDown), true);
            timelineSlider.AddHandler(MouseLeftButtonUpEvent, new MouseButtonEventHandler(timelineSlider_MouseLeftButtonUp), true);
            PWindow.Height = Screen.PrimaryScreen.WorkingArea.Height;
            ///////
            rotateAnimation = new DoubleAnimation(0, 360, rotateDuration);
            rotateAnimation.Completed += rotateAnimation_Completed;
        }

        private bool CheckDataBaseEngine()
        {
            try
            {
                Properties.Settings ps = new Properties.Settings();
                System.Data.OleDb.OleDbConnection oleCon = new System.Data.OleDb.OleDbConnection(ps.PLSConnectionString);
                oleCon.Open();
                return true;
            }
            catch (Exception ex)
            {
                if (ex.Message.IndexOf("Microsoft.ACE.OLEDB.12.0") != -1)
                {
                    DialogResult result = System.Windows.Forms.MessageBox.Show("На вашем компьютере не установлен Access Database Engine\nПерейти к загрузке необходимой службы?", "", MessageBoxButtons.YesNo, MessageBoxIcon.Error);
                    if (result == System.Windows.Forms.DialogResult.No)
                        return false;
                    if (result == System.Windows.Forms.DialogResult.Yes)
                    {
                        result = System.Windows.Forms.MessageBox.Show("Сейчас в Вашем браузере откроется станица для загрузки\nПосле установки службы снова запустите приложение", "", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        if (result == System.Windows.Forms.DialogResult.OK)
                            System.Diagnostics.Process.Start("http://www.microsoft.com/en-us/download/details.aspx?id=23734");
                        return false;
                    }
                }
            }
            return false;
        }

        private void PWindow_Initialized(object sender, EventArgs e)
        {
            core.LoadProgram();
        }

        #region Закрытие, перетаскивание и прочее

        private void Window_Closing_1(object sender, System.ComponentModel.CancelEventArgs e)
        {
            core.CloseAplication();
        }

        private void Sunset_Player_StateChanged(object sender, EventArgs e)
        {
            if (this.WindowState == System.Windows.WindowState.Maximized)
                this.WindowState = System.Windows.WindowState.Normal;
        }

        private void Close_Click(object sender, RoutedEventArgs e)
        {
            this.Close();
        }

        private void Minimize_Click(object sender, RoutedEventArgs e)
        {
            WindowState = System.Windows.WindowState.Minimized;
        }

        private void Border_MouseLeftButtonDown_1(object sender, MouseButtonEventArgs e)
        {
            this.DragMove();
            core.WindowSticking(PlayerBody);
        }


        private void TopButton_Click(object sender, RoutedEventArgs e)
        {
            core.ChangeTopMost();
        }
        #endregion

        #region Кнопки управления

        private void PlayButton_MouseRightButtonUp(object sender, MouseButtonEventArgs e)
        {
            core.Stop();
        }

        private void Window_MouseWheel_1(object sender, MouseWheelEventArgs e)
        {
            core.ChangeSliderValue(timelineSlider.Value - e.Delta / 10);
        }

        private void PlayButton_Click(object sender, RoutedEventArgs e)
        {
            core.PlayPause();
        }

        private void ToTray_Click(object sender, RoutedEventArgs e)
        {
            core.ToTray_Func();
        }

        private void StopButton_Click(object sender, RoutedEventArgs e)
        {
            core.Stop();
        }

        private void PrevButton_Click(object sender, RoutedEventArgs e)
        {
            core.PrevTrack();
        }

        private void NextButton_Click(object sender, RoutedEventArgs e)
        {
            core.NextTrack();
        }

        private void ListButton_Click(object sender, RoutedEventArgs e)
        {
            OpenCloseTitle('l');
        }

        private void SearchButton_Click(object sender, RoutedEventArgs e)
        {
            OpenCloseTitle('w');
        }

        private void volumeSlider_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
        {
            // core.ChangeVolume((double)volumeSlider.Value / 10);
        }

        private void RandomButton_Click(object sender, RoutedEventArgs e)
        {
            core.shufflePlay = RandomButton.IsChecked.Value;
        }

        private void Repeat_Click(object sender, RoutedEventArgs e)
        {
            core.repeatPlay = RepeatButton.IsChecked.Value;
        }

        private void TopBorder_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            this.DragMove();
        }

        private void timelineSlider_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
        {
            core.ChangeTime(e.NewValue);
        }

        private void timelineSlider_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            core.sliderpressed = true;
        }

        private void timelineSlider_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            double k = timelineSlider.Width / timelineSlider.Maximum;
            core.ChangeSliderValue(e.GetPosition(timelineSlider).X / k);
            core.sliderpressed = false;
        }
        #endregion

        #region Изменение иконок


        public void ChangeIcons(char comand)
        {
            string currentDir = System.IO.Path.GetDirectoryName(System.Windows.Forms.Application.ExecutablePath);
            OpenCloseTitle(comand);
            if (comand == 'p')
            {
                PauseIcon.Visibility = System.Windows.Visibility.Visible;
                PlayIcon.Visibility = System.Windows.Visibility.Hidden;
                try
                {
                    Uri iconUri = new Uri(currentDir + @"\Themes\Icons\Play.ico", UriKind.RelativeOrAbsolute);
                    this.Icon = BitmapFrame.Create(iconUri);
                }
                catch { }
            }
            if (comand == 's')
            {
                try
                {
                    Uri iconUri = new Uri(currentDir + @"\Themes\Icons\Logo.ico", UriKind.RelativeOrAbsolute);
                    this.Icon = BitmapFrame.Create(iconUri);
                }
                catch { }
                if (PauseIcon.Visibility == System.Windows.Visibility.Visible)
                {
                    PauseIcon.Visibility = System.Windows.Visibility.Hidden;
                    PlayIcon.Visibility = System.Windows.Visibility.Visible;
                }
            }
            if (comand == 'a')
            {
                try
                {
                    Uri iconUri = new Uri(currentDir + @"\Themes\Icons\Pause.ico", UriKind.RelativeOrAbsolute);
                    this.Icon = BitmapFrame.Create(iconUri);
                }
                catch { }
                PauseIcon.Visibility = System.Windows.Visibility.Hidden;
                PlayIcon.Visibility = System.Windows.Visibility.Visible;
            }
        }

        #endregion
        #endregion
        //-------------------------------------------------------------------------------------
        #region Анимация

        void WindowToBodyAnimations_Completed(object sender, EventArgs e)
        {
            PlayerHead.Height = 50;
            PlayerHead.Visibility = System.Windows.Visibility.Hidden;
            if (isTop)
                TopSplitGrid.Height = new GridLength(0);
            if (webWinOpened)
            {
                webWinOpened = false;
                OpenCloseTitle('w');
            }
            else
                WebList.Visibility = System.Windows.Visibility.Hidden;
            if (locWinOpened)
            {
                locWinOpened = false;
                OpenCloseTitle('l');
            }
            else
                LocalList.Visibility = System.Windows.Visibility.Hidden;
        }

        void BodyToWindowAnimations_Completed(object sender, EventArgs e)
        {
            PlayerHead.Height = openedWindowHeight;
        }

        void WindowToTitleAnimations_Completed(object sender, EventArgs e)
        {
            if (isTop)
                TopSplitGrid.Height = new GridLength(0);
            PlayerHead.Height = 76;
            if (webWinOpened)
            {
                webWinOpened = false;
                OpenCloseTitle('w');
            }
            else
                WebList.Visibility = System.Windows.Visibility.Hidden;
            if (locWinOpened)
            {
                locWinOpened = false;
                OpenCloseTitle('l');
            }
            else
                LocalList.Visibility = System.Windows.Visibility.Hidden;
        }

        void TitleToWindowAnimations_Completed(object sender, EventArgs e)
        {
            PlayerHead.Height = openedWindowHeight;
        }

        private void LeftSpoilerGrid_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            if (LeftSpoilerIcon.Visibility == System.Windows.Visibility.Visible)
            {
                OpenCloseSpoiler('l');
            }
        }

        private void TitleBkg_MouseEnter(object sender, System.Windows.Input.MouseEventArgs e)
        {
            if (ArtistTitle.Visibility == System.Windows.Visibility.Visible && sizeChange == false && ArtistTitle.Content.ToString() != "Ничего не выбрано")
            {
                ArtistTitle.Visibility = System.Windows.Visibility.Hidden;
                timelineSlider.Visibility = System.Windows.Visibility.Visible;
            }
        }

        private void LeftSpoilerGrid_MouseLeave(object sender, System.Windows.Input.MouseEventArgs e)
        {
            LeftSpoilerIcon.Opacity = 0.7;
        }

        private void LeftSpoilerGrid_MouseEnter(object sender, System.Windows.Input.MouseEventArgs e)
        {
            LeftSpoilerIcon.Opacity = 1;
        }

        /// <param name="nick">'l' - left, 'r' - right</param>
        private void OpenCloseSpoiler(char nick)
        {
            RotateTransform rotateTransform1;
            if (spoilerOpen)
            {
                if (nick == 'l')
                {
                    SpoilerGrid.BeginAnimation(MarginProperty, leftCloseAnimation);
                    spoilerOpen = false;
                }
                if (nick == 'r')
                {
                    SpoilerGrid.BeginAnimation(MarginProperty, rightCloseAnimation);
                    spoilerOpen = false;
                }
                rotateTransform1 = new RotateTransform(90);
                LeftSpoilerIcon.RenderTransform = rotateTransform1;
                rotateTransform1 = new RotateTransform(270);
                RightSpoilerIcon.RenderTransform = rotateTransform1;
            }
            else
            {
                if (nick == 'l')
                {
                    SpoilerGrid.BeginAnimation(MarginProperty, leftOpenAnimation);
                    spoilerOpen = true;
                }
                if (nick == 'r')
                {
                    SpoilerGrid.BeginAnimation(MarginProperty, rightOpenAnimation);
                    spoilerOpen = true;
                }
                rotateTransform1 = new RotateTransform(270);
                LeftSpoilerIcon.RenderTransform = rotateTransform1;
                rotateTransform1 = new RotateTransform(90);
                RightSpoilerIcon.RenderTransform = rotateTransform1;
            }
        }

        /// <param name="nick">'l' - local list; 't' - title, 's' - stop, 'w' - web list</param>
        public void OpenCloseTitle(char nick)
        {
            TitleToWindowAnimations.To = openedWindowHeight;
            BodyToWindowAnimations.To = openedWindowHeight;
            WindowToBodyAnimations.From = openedWindowHeight;
            WindowToTitleAnimations.From = openedWindowHeight;
            PlayerHead.Visibility = System.Windows.Visibility.Visible;
            Properties.Settings ps = Properties.Settings.Default;
            switch (nick)
            {
                case 't':
                    if (locWinOpened)
                        return;
                    if (core.mediaIsStop)
                    {

                        PlayerHead.BeginAnimation(HeightProperty, TitleToBodyAnimatoins);
                        titleOpened = false;
                    }
                    else
                    {
                        PlayerHead.BeginAnimation(HeightProperty, BodyToTitleAnimations);
                        titleOpened = true;

                    }
                    break;
                case 'l':
                    if (locWinOpened)
                    {
                        locWinOpened = false;
                        if (core.mediaIsStop || !ps.ShowTitleInMinimal)
                        {
                            PlayerHead.BeginAnimation(HeightProperty, WindowToBodyAnimations);
                            titleOpened = false;
                        }
                        else
                        {
                            PlayerHead.BeginAnimation(HeightProperty, WindowToTitleAnimations);
                            ShowHideSizeGrip(false);
                        }
                    }
                    else
                    {

                        if (webWinOpened)
                        {
                            locWinOpened = true;
                            goto case 'w';
                        }
                        LocalList.Visibility = System.Windows.Visibility.Visible;
                        if (titleOpened)
                            PlayerHead.BeginAnimation(HeightProperty, TitleToWindowAnimations);
                        else
                            PlayerHead.BeginAnimation(HeightProperty, BodyToWindowAnimations);
                        ShowHideSizeGrip(true);
                        if (isTop)
                            TopSplitGrid.Height = new GridLength(20);
                        locWinOpened = true;
                        titleOpened = true;
                    }
                    break;
                case 'w':
                    if (webWinOpened)
                    {
                        webWinOpened = false;
                        if (core.mediaIsStop || !ps.ShowTitleInMinimal)
                        {
                            PlayerHead.BeginAnimation(HeightProperty, WindowToBodyAnimations);
                            titleOpened = false;
                        }
                        else
                        {
                            PlayerHead.BeginAnimation(HeightProperty, WindowToTitleAnimations);
                            ShowHideSizeGrip(false);
                        }
                    }
                    else
                    {
                        if (locWinOpened)
                        {
                            webWinOpened = true;
                            goto case 'l';
                        }
                        if (core.LogIn(false))
                        {
                            WebList.Visibility = System.Windows.Visibility.Visible;
                            if (titleOpened)
                                PlayerHead.BeginAnimation(HeightProperty, TitleToWindowAnimations);
                            else
                                PlayerHead.BeginAnimation(HeightProperty, BodyToWindowAnimations);
                            ShowHideSizeGrip(true);
                            if (isTop)
                                TopSplitGrid.Height = new GridLength(20);
                            webWinOpened = true;
                            titleOpened = true;
                        }
                    }
                    break;
            }
        }



        private void RightSpoilerGrid_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            if (RightSpoilerIcon.Visibility == System.Windows.Visibility.Visible)
                OpenCloseSpoiler('r');
        }

        private void RightSpoilerGrid_MouseEnter(object sender, System.Windows.Input.MouseEventArgs e)
        {
            RightSpoilerIcon.Opacity = 1;
        }

        private void RightSpoilerGrid_MouseLeave(object sender, System.Windows.Input.MouseEventArgs e)
        {
            RightSpoilerIcon.Opacity = 0.7;
        }

        private void RotateWindow()
        {
            if (isTop)
            {
                PlayerBody.VerticalAlignment = System.Windows.VerticalAlignment.Bottom;
                SpoilerGrid.VerticalAlignment = System.Windows.VerticalAlignment.Bottom;
                PlayerHead.VerticalAlignment = System.Windows.VerticalAlignment.Bottom;
                TitleGrid.VerticalAlignment = System.Windows.VerticalAlignment.Top;
                BottomSplitGrid.Height = new GridLength(30);
                TopSplitGrid.Height = new GridLength(4);
                PlayerHead.Margin = new Thickness(0, 0, 0, 6);
                Grid.SetRow(TitleGrid, 1);
                isTop = false;
            }
            else
            {
                PlayerBody.VerticalAlignment = System.Windows.VerticalAlignment.Top;
                SpoilerGrid.VerticalAlignment = System.Windows.VerticalAlignment.Top;
                PlayerHead.VerticalAlignment = System.Windows.VerticalAlignment.Top;
                TitleGrid.VerticalAlignment = System.Windows.VerticalAlignment.Bottom;
                BottomSplitGrid.Height = new GridLength(4);
                TopSplitGrid.Height = new GridLength(20);
                PlayerHead.Margin = new Thickness(0);
                Grid.SetRow(TitleGrid, 5);
                isTop = true;
            }

        }

        private void Rotate_Click(object sender, RoutedEventArgs e)
        {
            RotateWindow();
        }

        public void NavigateWindow()
        {
            //Правая часть монитора
            if (this.Left + this.Width + 5 > Screen.PrimaryScreen.WorkingArea.Width)
            {
                if (LeftSpoilerIcon.Visibility == System.Windows.Visibility.Hidden)
                {
                    if (spoilerOpen)
                    {
                        OpenCloseSpoiler('l');
                        OpenCloseSpoiler('l');
                    }
                    WindowButtonGrid.HorizontalAlignment = System.Windows.HorizontalAlignment.Left;
                    LeftSpoilerIcon.Visibility = System.Windows.Visibility.Visible;
                    RightSpoilerIcon.Visibility = System.Windows.Visibility.Hidden;
                    PlayerBody.HorizontalAlignment = System.Windows.HorizontalAlignment.Right;
                    PlayerHead.HorizontalAlignment = System.Windows.HorizontalAlignment.Right;
                    Grid.SetColumn(CloseWGrid, 0);
                    Grid.SetColumn(SettingsGrid, 0);
                    Grid.SetColumn(MinimizeGrid, 2);
                    Grid.SetColumn(RotateGrid, 2);
                    return;
                }
            }
            //Левая часть монитора
            else
            {
                if (LeftSpoilerIcon.Visibility == System.Windows.Visibility.Visible)
                {
                    if (spoilerOpen)
                    {
                        OpenCloseSpoiler('r');
                        OpenCloseSpoiler('r');
                    }
                    WindowButtonGrid.HorizontalAlignment = System.Windows.HorizontalAlignment.Right;
                    LeftSpoilerIcon.Visibility = System.Windows.Visibility.Hidden;
                    RightSpoilerIcon.Visibility = System.Windows.Visibility.Visible;
                    PlayerBody.HorizontalAlignment = System.Windows.HorizontalAlignment.Left;
                    PlayerHead.HorizontalAlignment = System.Windows.HorizontalAlignment.Left;
                    Grid.SetColumn(CloseWGrid, 2);
                    Grid.SetColumn(SettingsGrid, 2);
                    Grid.SetColumn(MinimizeGrid, 0);
                    Grid.SetColumn(RotateGrid, 0);
                    return;
                }
            }
        }

        private void PlayerBody_MouseEnter(object sender, System.Windows.Input.MouseEventArgs e)
        {
            if (ArtistTitle.Visibility == System.Windows.Visibility.Hidden)
            {
                ArtistTitle.Visibility = System.Windows.Visibility.Visible;
                timelineSlider.Visibility = System.Windows.Visibility.Hidden;
            }
        }

        private void BottomGripBkg_MouseMove(object sender, System.Windows.Input.MouseEventArgs e)
        {
            if (ArtistTitle.Visibility == System.Windows.Visibility.Hidden)
            {
                ArtistTitle.Visibility = System.Windows.Visibility.Visible;
                timelineSlider.Visibility = System.Windows.Visibility.Hidden;
            }
        }

        private void TopGripBkg_MouseMove(object sender, System.Windows.Input.MouseEventArgs e)
        {
            if (ArtistTitle.Visibility == System.Windows.Visibility.Hidden)
            {
                ArtistTitle.Visibility = System.Windows.Visibility.Visible;
                timelineSlider.Visibility = System.Windows.Visibility.Hidden;
            }
        }

        void rotateAnimation_Completed(object sender, EventArgs e)
        {
            BeginRotateAnimation();
        }

        public void BeginRotateAnimation()
        {
            if (doAnimation)
            {
                System.Windows.Shapes.Path path = UserUpdateIcon;
                RotateTransform rt = new RotateTransform();
                path.RenderTransform = rt;
                rt.BeginAnimation(RotateTransform.AngleProperty, rotateAnimation);
            }
        }
        #endregion
        //-------------------------------------------------------------------------------------
        #region Локальный плейлист

        private void AddNewPL_Click(object sender, RoutedEventArgs e)
        {
            AddNewPlFunc(null);
        }

        /// <param name="name"> if name is null or conflicts, that given name "Playlist №"</param>
        private void AddNewPlFunc(string name)
        {
            if (name != null && PLNameBox.Items.IndexOf(name) == -1)
            {
                core.AddNewPL(name);
                PLNameBox.Items.Add(name);
                PLNameBox.SelectedItem = name;
            }
            else
            {
                for (int i = 0; i < 1000; i++)
                {
                    name = "Playlist " + i;
                    if (PLNameBox.Items.IndexOf(name) == -1)
                    {
                        core.AddNewPL(name);
                        PLNameBox.Items.Add(name);
                        PLNameBox.SelectedItem = name;
                        break;
                    }
                }
            }
        }

        private void DelPL_Click(object sender, RoutedEventArgs e)
        {
            if (PLNameBox.Items.Count > 0)
            {
                int ind = PLNameBox.SelectedIndex - 1;
                var result = System.Windows.MessageBox.Show("Удалить плейлист?", "", MessageBoxButton.YesNo, MessageBoxImage.Question, MessageBoxResult.Yes);
                if (result == MessageBoxResult.Yes)
                {
                    core.DeletePL(PLNameBox.SelectedItem.ToString());
                    PLNameBox.Items.Remove(PLNameBox.SelectedItem);
                    if (ind > 0)
                        PLNameBox.SelectedIndex = ind;
                    else
                        PLNameBox.SelectedIndex = 0;
                }
            }
        }

        System.Windows.Forms.OpenFileDialog open;
        private void ViewExplorer_Click(object sender, RoutedEventArgs e)
        {
            open = new System.Windows.Forms.OpenFileDialog();
            open.Multiselect = true;
            open.Filter = "Музыка(*.mp3,*.wav,*.wma, *.flac)|*.mp3;*.wav;*.wma;*.flac;";
            if (open.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                string[] openedFile = open.FileNames;
                core.AddTrackToPL(openedFile);
            }
        }

        private void PLNameBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (e.AddedItems.Count != 0)
                core.SelectLocalPL(e.AddedItems[0].ToString());

        }

        private void PLNameBox_MouseDoubleClick(object sender, MouseButtonEventArgs e)
        {

        }

        private void PLNameBox_KeyDown(object sender, System.Windows.Input.KeyEventArgs e)
        {
            if (e.Key == Key.Enter)
            {

            }
            if (e.Key == Key.Escape)
            {
                PLNameBox.IsEditable = false;
            }
        }

        private void PLNameBox_Drop(object sender, System.Windows.DragEventArgs e)
        {
            if (e.Data.GetDataPresent(System.Windows.DataFormats.FileDrop))
            {
                string[] files = (string[])e.Data.GetData(System.Windows.DataFormats.FileDrop);
                string dir = files[0];
                if (Directory.Exists(dir))
                {
                    dir = dir.Remove(0, dir.LastIndexOf("\\") + 1);
                    AddNewPlFunc(dir);
                }
                else
                    AddNewPlFunc(null);
                core.AddTrackToPL(files);
            }
        }

        private void local_Drop(object sender, System.Windows.DragEventArgs e)
        {
            if (e.Data.GetDataPresent(System.Windows.DataFormats.FileDrop))
            {
                string[] files = (string[])e.Data.GetData(System.Windows.DataFormats.FileDrop);
                if (PLNameBox.Items.Count == 0)
                {
                    string dir = files[0];
                    if (Directory.Exists(dir))
                    {
                        dir = dir.Remove(0, dir.LastIndexOf("\\") + 1);
                        AddNewPlFunc(dir);
                    }
                    else
                        AddNewPlFunc(null);
                }
                core.AddTrackToPL(files);
            }
        }

        private void local_MouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            core.Play((DataRowView)local.SelectedValue);
        }

        private void local_ContextMenuOpening(object sender, ContextMenuEventArgs e)
        {
            core.ShowItemContexMenu((DataRowView)local.SelectedValue);
        }

        private void PLNameBox_MouseMove(object sender, System.Windows.Input.MouseEventArgs e)
        {
            PLNameBox.Focus();
        }

        #endregion
        //-------------------------------------------------------------------------------------        
        #region Изменение размера листа

        private void ShowHideSizeGrip(bool show)
        {
            if (show)
            {
                if (isTop)
                {
                    Grid.SetRowSpan(TitleGrid, 1);
                    BottomSizeLine.Visibility = System.Windows.Visibility.Visible;
                }
                else
                {
                    Grid.SetRow(TitleGrid, 1);
                    Grid.SetRowSpan(TitleGrid, 1);
                    TopSizeLine.Visibility = System.Windows.Visibility.Visible;
                }
            }
            else
            {
                if (isTop)
                {
                    Grid.SetRowSpan(TitleGrid, 2);
                    BottomSizeLine.Visibility = System.Windows.Visibility.Hidden;
                }
                else
                {
                    Grid.SetRow(TitleGrid, 0);
                    Grid.SetRowSpan(TitleGrid, 2);
                    TopSizeLine.Visibility = System.Windows.Visibility.Hidden;
                }
            }
        }

        private void BackgroundGrid_MouseMove(object sender, System.Windows.Input.MouseEventArgs e)
        {
            if (e.LeftButton == MouseButtonState.Released)
            {
                sizeChange = false;
                BackgroundGrid.Visibility = System.Windows.Visibility.Hidden;
            }
            if (sizeChange)
            {
                if (isTop)
                    openedWindowHeight = e.GetPosition(TopSizeLine).Y + 5;
                else
                    openedWindowHeight = Math.Abs(e.GetPosition(BottomSizeLine).Y) + 5;
                if (openedWindowHeight > 220)
                    PlayerHead.Height = openedWindowHeight;
            }
            if (ArtistTitle.Visibility == System.Windows.Visibility.Hidden)
            {
                ArtistTitle.Visibility = System.Windows.Visibility.Visible;
                timelineSlider.Visibility = System.Windows.Visibility.Hidden;
            }
        }

        private void TopBorder_MouseMove(object sender, System.Windows.Input.MouseEventArgs e)
        {
            if (e.LeftButton == MouseButtonState.Released)
            {
                sizeChange = false;
                BackgroundGrid.Visibility = System.Windows.Visibility.Hidden;
            }
            if (sizeChange)
            {
                if (isTop)
                    openedWindowHeight = e.GetPosition(TopSizeLine).Y + 5;
                else
                    openedWindowHeight = Math.Abs(e.GetPosition(BottomSizeLine).Y) + 5;
                if (openedWindowHeight > 220)
                    PlayerHead.Height = openedWindowHeight;
            }
            if (ArtistTitle.Visibility == System.Windows.Visibility.Hidden)
            {
                ArtistTitle.Visibility = System.Windows.Visibility.Visible;
                timelineSlider.Visibility = System.Windows.Visibility.Hidden;
            }
        }

        bool sizeChange = false;

        private void GripBkg_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            sizeChange = true;
            BackgroundGrid.Visibility = System.Windows.Visibility.Visible;
        }

        private void GripBkg_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            sizeChange = false;
            BackgroundGrid.Visibility = System.Windows.Visibility.Hidden;
        }

        #endregion
        //-------------------------------------------------------------------------------------
        #region Веб плейлист

        private void SearchBoxGroup_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (e.AddedItems.Count > 0)
                core.SelectBoxItem(e.AddedItems[0], selectedTab);
        }

        private void SearchBoxFriend_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (e.AddedItems.Count > 0)
                core.SelectBoxItem(e.AddedItems[0], selectedTab);
        }

        private void web_ContextMenuOpening(object sender, ContextMenuEventArgs e)
        {
            core.ShowWebContextMenu((System.Data.DataRowView)web.SelectedItem);
        }

        private void web_MouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            core.Play((System.Data.DataRowView)web.SelectedItem);
        }

        private void MyPageButton_Click(object sender, RoutedEventArgs e)
        {
            ShowHideTBGrid(true);
            if (selectedUserWall == true)
                selectedTab = 1;
            else
                selectedTab = 0;
            EnableSelectedTab();
            core.SelectWebTable(selectedTab, "user", "", false);
        }

        private void GroupPageButton_Click(object sender, RoutedEventArgs e)
        {
            core.ClearWebTable();
            ShowHideTBGrid(false);
            if (selectedGroupWall == true)
                selectedTab = 3;
            else
                selectedTab = 2;
            EnableSelectedTab();
            if (core.CreateGroupsList() == false)
                core.SelectWebTable(selectedTab, "group", "", false);

        }

        private void FriendPageButton_Click(object sender, RoutedEventArgs e)
        {
            core.ClearWebTable();
            ShowHideTBGrid(false);
            if (core.CreateFriendList() == false)
                core.SelectWebTable(selectedTab, "friend", "", false);
            if (selectedFriendWall == true)
                selectedTab = 5;
            else
                selectedTab = 4;
            EnableSelectedTab();
        }

        private void NewsPageButton_Click(object sender, RoutedEventArgs e)
        {
            core.ClearWebTable();
            selectedTab = 9;

        }

        private void AudioButton_Click(object sender, RoutedEventArgs e)
        {
            if (selectedTab % 2 == 1)
            {
                selectedTab--;
                EnableSelectedTab();
                core.SelectWebTable(selectedTab, CheckTabName(), "", false);
            }
        }

        public string CheckTabName()
        {
            if (selectedTab == 9)
                return "news";
            if (selectedTab < 2)
                return "user";
            if (selectedTab > 1 && selectedTab < 4)
                return "group";
            if (selectedTab > 3)
                return "friend";
            return "error";
        }

        private void WallButton_Click(object sender, RoutedEventArgs e)
        {
            if (selectedTab % 2 == 0)
            {
                selectedTab++;
                EnableSelectedTab();
                core.SelectWebTable(selectedTab, CheckTabName(), "", false);
            }
        }

        private void DisableAllTab()
        {
            Brush brush = (Brush)FindResource("TabControlItemBackgroundNormal");
            System.Windows.Controls.Button[] elemArr = { AudioButton, WallButton, MyPageButton, GroupPageButton, FriendPageButton, NewsPageButton };
            foreach (var but in elemArr)
                if (but.Background != brush)
                    but.Background = brush;
        }

        private void ShowHideTBGrid(bool show)
        {
            if (show)
            {
                TBGrid.Visibility = System.Windows.Visibility.Visible;
                CMBGrid.Visibility = System.Windows.Visibility.Hidden;
            }
            else
            {
                TBGrid.Visibility = System.Windows.Visibility.Hidden;
                CMBGrid.Visibility = System.Windows.Visibility.Visible;
            }
        }

        private void EnableSelectedTab()
        {
            DisableAllTab();
            Brush brush = (Brush)FindResource("DisabledArrowFrame");
            switch (selectedTab)
            {
                case 0:
                    MyPageButton.Background = brush;
                    AudioButton.Background = brush;
                    break;
                case 1:
                    MyPageButton.Background = brush;
                    WallButton.Background = brush;
                    break;
                case 2:
                    AudioButton.Background = brush;
                    GroupPageButton.Background = brush;
                    break;
                case 3:
                    GroupPageButton.Background = brush;
                    WallButton.Background = brush;
                    break;
                case 4:
                    AudioButton.Background = brush;
                    FriendPageButton.Background = brush;
                    break;
                case 5:
                    FriendPageButton.Background = brush;
                    WallButton.Background = brush;
                    break;
                case 6:
                    MyPageButton.Background = brush;
                    break;
            }
        }

        #endregion

        private void UpdateButtonUser_Click(object sender, RoutedEventArgs e)
        {
            switch (selectedTab)
            {
                case 0:
                case 1:
                    core.SelectWebTable(selectedTab, "user", "", true);
                    break;
                case 2:
                case 3:
                    core.SelectWebTable(selectedTab, "group", "", true);
                    break;
                case 4:
                case 5:
                    core.SelectWebTable(selectedTab, "friend", "", true);
                    break;
                case 6:
                    if (SearchBoxGroup.Text.Length != 0)
                        core.SelectWebTable(selectedTab, SearchBoxGroup.Text, "", true);
                    break;
            }
        }

        private void AlbumButton_Click(object sender, RoutedEventArgs e)
        {

        }

        private void SearchAudio_Button_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            if (SearchBoxMy.Text.Length > 0)
            {
                core.SelectWebTable(6, SearchBoxMy.Text, "", false);
                selectedTab = 6;
                EnableSelectedTab();
            }
        }

        private void SearchBoxMy_KeyDown(object sender, System.Windows.Input.KeyEventArgs e)
        {
            if (e.Key == Key.Enter)
                if (SearchBoxMy.Text.Length > 0)
                {
                    core.SelectWebTable(6, SearchBoxMy.Text, "", false);
                    selectedTab = 6;
                    EnableSelectedTab();
                }

        }

        private void UpdateButtonUser_MouseRightButtonDown(object sender, MouseButtonEventArgs e)
        {
            core.StopUpdate();
        }

        private void SettingsButton_Click(object sender, RoutedEventArgs e)
        {
            if (SettingsButton.IsEnabled)
            {
                Settings set = new Settings(core);
                SettingsButton.IsEnabled = false;
                set.Show();
                set.Closed += set_Closed;
            }
        }

        void set_Closed(object sender, EventArgs e)
        {
            SettingsButton.IsEnabled = true;
        }
    }
}
